/*
 moxl - Modular XML Library
 Copyright (c) 2007, Malcolm Sparks

 This program is free software; you can redistribute it and/or
 modify it under the terms of the GNU General Public License
 as published by the Free Software Foundation; either version 2
 of the License, or (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with this program; if not, write to the Free Software
 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 */
package moxl.parser;

import java.io.ByteArrayInputStream;
import java.io.InputStream;

import moxl.parser.markup.Markup;
import moxl.parser.markup.MarkupParser;
import moxl.parser.markup.MarkupStream;
import moxl.parser.markup.types.EndOfDocumentMarkup;
import moxl.parser.model.DocumentBuilder;
import moxl.parser.model.ParsedDocument;
import moxl.parser.model.ParsedElement;
import moxl.parser.resource.AnonymousStreamXmlResource;
import moxl.raw.XmlResource;
import moxl.raw.XmlResourceException;
import moxl.reader.Location;
import moxl.tokenizer.TokenizerException;

/**
 * An XML parser.
 */
public class XmlParser
{
	/**
	 * Parse an XML resource.
	 * 
	 * @param resource
	 *            supplies the actual input stream, identified with a name if possible.
	 * @return an object representing the unprocessed element node.
	 * @throws TokenizerException
	 * @throws XmlResourceException
	 * @throws ParserException
	 */
	public ParsedElement parse(XmlResource resource) throws TokenizerException, XmlResourceException, ParserException
	{
		ParsedDocument document = new ParsedDocument(resource);

		DocumentBuilder builder = new DocumentBuilder(document);
		MarkupParser markupParser = new MarkupParser();
		MarkupStream markupStream;
		markupStream = markupParser.parse(resource.getResourceAsStream());
		Markup markup;

		do
		{
			markup = markupStream.read();
			builder.addMarkup(markup);
		}
		while (!(markup instanceof EndOfDocumentMarkup));

		return document.getDocumentElement();
	}

	public ParsedElement parseString(String string) throws ParserException, TokenizerException, XmlResourceException
	{
		return parse(new ByteArrayInputStream(string.getBytes()));
	}

	public ParsedElement parse(InputStream in) throws ParserException, TokenizerException, XmlResourceException
	{
		if (in == null)
		{
			throw new ParserException("InputStream is null", new Location());
		}
		AnonymousStreamXmlResource resource = new AnonymousStreamXmlResource(in);
		return parse(resource);
	}
}
